<?php
if( !defined('CORE') ) exit('Request Error!');
/**
 * 用户管理
 *
 * @version $Id$
 */
class ctl_users
{
    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        tpl::assign('title', '用户管理');
        tpl::assign('cfg_groups', cls_access::$cfg_groups);
    }

    /**
     * 管理员帐号管理
     */
    public function index()
    {
        $where = array();
        $gp = req::item('gp', '');
        if (!empty($gp)) 
        {
            $where[] = "`groups` LIKE '%{$gp}%'";
            $url = "&gp=" . $gp;
        }
        $where = empty($where) ? '' : 'WHERE ' . implode(' AND ', $where);

        $sql = "SELECT * FROM `users` {$where}";
        $list = db::get_all($sql);
        tpl::assign('list', $list);
        tpl::display('users.index.tpl');
    }

    public function add()
    {
        if (!empty(req::$posts)) 
        {
            req::$forms['pools'] = 'admin';
            if(empty(req::$forms['groups']))
            {
                req::$forms['groups'] = 'member_pub';
            } 
            else 
            {
                $gp = join(',', req::$forms['groups']);
                req::$forms['groups'] = $gp;
            }
            $user_name = req::item('user_name');
            $row = db::get_one("SELECT * FROM `users` WHERE `user_name`='{$user_name}'");
            if( is_array($row) )
            {
                mod_msgbox::show('系统提示', '用户名已经存在！', '-1');
                exit();
            }
            if( req::$forms['userpwd']=='' )
            {
                mod_msgbox::show('系统提示', '用户密码不能为空！', '-1');
                exit();
            }
            req::$forms['userpwd'] = md5(req::$forms['userpwd']);
            req::$forms['regtime'] = time();
            req::$forms['regip']   = util::get_client_ip();
            db::insert('users', req::$forms);
            cls_access::save_log(cls_access::$accctl->fields['user_name'], "增加了一个管理员");

            $gourl = '?ct=users&ac=index';
            mod_msgbox::show("用户管理", "添加成功", $gourl);

        }
        else 
        {
            tpl::display('users.add.tpl');
        }
    }

    public function edit()
    {
        $uid = req::item('uid', 0);
        if (!empty(req::$posts)) 
        {
            if (req::item('userpwd') != req::item('userpwdok')) 
            {
                mod_msgbox::show("用户管理", "修改失败，两次输入密码不同", -1);
            }

            if(req::item('userpwd') != '')
            {
                req::$forms['userpwd'] = md5(req::$forms['userpwd']);
            } 
            else 
            {
                unset(req::$forms['userpwd']);
            }
            //保存附表数据
            if(empty(req::$forms['groups']))
            {
                req::$forms['groups'] = 'member_pub';
            } 
            else 
            {
                $gp = join(',', req::$forms['groups']);
                req::$forms['groups'] = $gp;
            }
            $uid = intval(req::item('uid', 0));
            db::update('users', req::$forms, "`uid`=" . $uid);

            cls_access::del_cache($uid);
            cls_access::save_log(cls_access::$accctl->fields['user_name'], "修改了管理员 ".req::item('uid')." 的密码！");

            $gourl = '?ct=users&ac=index';
            mod_msgbox::show("用户管理", "修改成功", $gourl);

        }
        else 
        {
            $sql = "SELECT * FROM `users` WHERE `uid`={$uid} LIMIT 1";
            $v = db::get_one($sql);
            tpl::assign('v', $v);
            tpl::display('users.edit.tpl');
        }
    }

    public function del()
    {
        $uids = implode(',', req::item('uid', 0));
        $sql = "DELETE FROM `users` WHERE `uid` IN ({$uids})";
        db::query($sql);
        cls_access::save_log(cls_access::$accctl->fields['user_name'], "删除了管理员 " . $uids);

        $gourl = '?ct=users&ac=index';
        mod_msgbox::show("用户管理", "删除成功", $gourl);
    }

    /**
     * 对修改用户自己的密码使用单独事件
     */
    public function editpwd()
    {
        $uid = cls_access::$accctl->uid;
        if (!empty(req::$posts)) 
        {
            $userpwd = req::item('userpwd', '');
            if( $userpwd == '')
            {
                mod_msgbox::show("用户管理", "修改失败，密码不能为空", -1);
            } 
            $userpwd = md5($userpwd);

            if (req::item('userpwd') != req::item('userpwdok')) 
            {
                mod_msgbox::show("用户管理", "修改失败，两次输入密码不同", -1);
            }

            $sql = "UPDATE `users` SET `userpwd`='{$userpwd}' WHERE `uid`={$uid}";
            db::query($sql);

            cls_access::save_log(cls_access::$accctl->fields['user_name'], "修改密码");

            $gourl = empty($_SERVER['HTTP_REFERER']) ? '?ct=users&ac=index' : $_SERVER['HTTP_REFERER'];
            mod_msgbox::show("用户管理", "修改成功", $gourl);

        }
        else 
        {
            $sql = "SELECT * FROM `users` WHERE `uid`={$uid} LIMIT 1";
            $v = db::get_one($sql);
            tpl::assign('v', $v);
            tpl::display('users.edit.me.tpl');
        }
    }

    /**
     * 设置具体用户的权限
     */
    public function user_purview()
    {
        $config_apps = self::get_config_apps();
        $even = req::item('even', '');

        $uid  = intval(req::item('uid', 0));
        //显示用户原有权限
        if( $even == '' )
        {
            $fields = db::get_one("Select * From `users` where `uid`='{$uid}' ");
            $groups = cls_access_cfg::get_acc_groups($fields['uid'], 'admin', $fields['groups']);
            tpl::assign('users', $fields);
            tpl::assign('groups', $groups);
            tpl::assign('config_apps', $config_apps);
            tpl::assign('user_name', $fields['user_name']);
            tpl::assign('uid', $fields['uid']);
            tpl::assign('gp', $fields['groups']);
        }
        //保存修改
        else if( $even == 'saveedit' )
        {
            $groups = req::item('groups', '');
            $gp     = req::item('gp', '');
            $gstr   = join(',', $groups);
            cls_access::del_cache($uid);
            cache::del('upurview', $uid);
            db::query("Replace Into `users_purview`(`uid`, `purviews`) Values('{$uid}', '{$gstr}'); ");
            mod_msgbox::show('系统提示', '成功指定用户的独立权限！', '?ct=users&ac=index&gp='.$gp);
            exit();
        }
        tpl::assign('cfg_groups', cls_access::$cfg_groups['pools']['admin']);
        tpl::display('users.purview.tpl');
        exit();
    }

    public function user_purview_del()
    {
        $uid  = intval(req::item('uid', 0));
        $sql = "DELETE FROM `users_purview` WHERE `uid`={$uid}";
        db::query($sql);
        $gourl = empty($_SERVER['HTTP_REFERER']) ? '?ct=users&ac=index' : $_SERVER['HTTP_REFERER']; 
        mod_msgbox::show('系统提示', '成功清除用户的独立权限！', $gourl);
    }

    /**
     * 分析属性
     * @parem string $attstr
     * @return array
     */
    protected static function parse_atts($attstr)
    {
        $patts = '';
        preg_match_all("/([0-9a-z_-]*)[\t ]{0,}=[\t ]{0,}[\"']([^>\"']*)[\"']/isU", $attstr, $patts);
        if( !isset($patts[1]) )
        {
            return false;
        }
        $atts = array();
        foreach($patts[1] as $ak=>$attname)
        {
            $atts[trim($attname)] = trim($patts[2][$ak]);
        }
        return $atts;
    }

    /**
     * 从属性数组中读取一个元素
     * @parem $atts
     * @parem $key
     * @parem $df = ''
     * @return string
     */
    protected static function get_att(&$atts, $key, $df='')
    {
        return isset($atts[$key]) ? trim($atts[$key]) : $df;
    }

    /**
     * 当前用户登录后列出它的权限
     */
    public function mypurview()
    {
        $config_apps = self::get_config_apps();

        $acc_ctl = cls_access::get_instance();
        $groups = cls_access_cfg::get_acc_groups($acc_ctl->fields['uid'], 'admin', $acc_ctl->fields['groups']);
        tpl::assign('users', $acc_ctl->fields);
        tpl::assign('groups', $groups);
        tpl::assign('config_apps', $config_apps);
        tpl::display('users.mypurview.tpl');
        exit();
    }

    /**
     * 修改组权限
     */
    public function edit_purview_groups()
    {
        $config_apps = self::get_config_apps();
        $even = req::item('even', '');
        tpl::assign('even', $even);
        $gp = req::item('group', '');
        $acc_ctl = cls_access::get_instance();
        if( $gp != '')
        {
            list($poolname, $gp) = explode('_', $gp);
        }
        tpl::assign('group_name', '所有组');
        //修改具体组
        if( $even == 'edit' )
        {
            tpl::assign('group_name', cls_access::$cfg_groups['pools'][$poolname]['private'][$gp]['name']);
            tpl::assign('config_apps', $config_apps);
            tpl::assign('cfg_groups', cls_access::$cfg_groups);
            tpl::assign('groups', cls_access::$cfg_groups['pools'][$poolname]['private'][$gp]);
            //print_r( cls_access::$cfg_groups['pools'][$poolname]['private'][$gp] );
        }
        //保存修改
        else if( $even == 'saveedit' )
        {

            $groups = req::item('groups', '');
            if ( !empty($groups) )
            {
                $gstr = join(',', $groups);
            }
            else
            {
                $gstr = array();
            }
            $groups = cls_access_cfg::str_gps($gstr);
            cls_access::$cfg_groups['pools'][$poolname]['private'][$gp]['allow'] = $groups;
            $new_config = cls_access_cfg::save_group_config( cls_access::$cfg_groups );
            mod_msgbox::show('系统提示', '成功修改指定的组权限！', '?ct=users&ac=edit_purview_groups&even=edit&group='.$poolname.'_'.$gp);
            exit();
        }
        tpl::assign('access_groups', cls_access::$cfg_groups);
        tpl::display('users.edit_purview_groups.tpl');
        exit();
    }

    public function add_purview_groups()
    {
        log::add('test', json_encode(req::$forms));
    	$config_apps = self::get_config_apps();
    	$acc_ctl = cls_access::get_instance();
    	tpl::assign('group_name', '所有组');
        $even = req::item('even', '');
    
    	//保存修改
    	if($even == 'addsave')
    	{
    		$poolname = 'admin';
    		$group_name = trim(req::$posts['group_name']);
    		if(empty($group_name))
    		{
    			mod_msgbox::show('系统提示', '用户组名称不能为空！', -1);
    		}
    
    		$group_name_pingyin = util::pinyin($group_name);
    		$group_name_array = array_keys(cls_access::$cfg_groups['pools'][$poolname]['private']);
    		if(empty($group_name_pingyin)  || in_array($group_name_pingyin,$group_name_array))
    		{
    			mod_msgbox::show('系统提示', '用户组名称异常或者已经添加该用户组！', -1);
    		}
    
    		$groups = req::item('groups', '');
    		$gstr = join(',', $groups);
    
    		$groups = cls_access_cfg::str_gps($gstr);
    
    		$gp = $group_name_pingyin;
    		cls_access::$cfg_groups['pools'][$poolname]['private'][$gp]['allow'] = $groups;
    		cls_access::$cfg_groups['pools'][$poolname]['private'][$gp]['name'] = $group_name;
    		$new_config = cls_access_cfg::save_group_config( cls_access::$cfg_groups );
    
    		mod_msgbox::show('系统提示', '成功增加用户组权限！', '?ct=users&ac=edit_purview_groups');
    		exit();
    	}
    	else
    	{
    		tpl::assign('config_apps', $config_apps);
    		tpl::assign('cfg_groups', cls_access::$cfg_groups);
    		tpl::assign('access_groups', cls_access::$cfg_groups);
    		tpl::display('users.add_purview_groups.tpl');
    	}
    }



    /**
     * 操作日志
     */
    public function log()
    {
        $where = array();
        $url = "";
        $keyword = req::item('keyword', '');
        if (!empty($keyword)) 
        {
            $where[] = "CONCAT(`user_name`, `operate_msg`) LIKE '%{$keyword}%'";
            $url = "&keyword=" . $keyword;
        }
        $where = empty($where) ? '' : 'WHERE ' . implode(' AND ', $where);

        $sql = "SELECT COUNT(*) AS count FROM `users_admin_log` {$where}";
        $row = db::get_one($sql);
        $config['current_page'] = req::item('page_no', 1);   //当前页数,至少为1
        $config['page_size']    = 20;      //每页显示多少条
        $config['total_rs']     = $row['count'];      //总记录数
        $config['url_prefix']   = '?ct=users&ac=log' . $url;     //网址前缀
        $config['page_name']    = 'page_no';  //当前分页变量名(默认是page_no,即访问是用 url_prefix&page_no=xxx )
        $config['move_size']    = 5;    //前后偏移量（默认是5）
        $config['input']        = 0;    //是否使用输入跳转框(0|1)
        $pages = util::pagination($config);

        $offset = ( $config['current_page'] - 1 ) * $config['page_size'];
        $sql = "SELECT * FROM `users_admin_log` {$where} ORDER BY `id` DESC LIMIT {$offset}, {$config['page_size']}";
        $list = db::get_all($sql);

        //echo '<pre>';print_r($list);echo '</pre>';
        tpl::assign( 'list', $list );
        tpl::assign( 'pages', $pages );
        tpl::display( 'users.log.tpl' );
    }

    /**
     * 删除操作日志
     */
    public function log_del()
    {
        $ids = req::item('id', array());
        if (empty($ids)) 
        {
            mod_msgbox::show("用户管理", "删除失败,请选择要删除的日志", -1);
        }

        $ids = implode(',', $ids);
        $sql = "DELETE FROM `users_admin_log` WHERE `id` IN ({$ids})";
        db::query($sql);
        $gourl = empty($_SERVER['HTTP_REFERER']) ? '?ct=users&ac=log' : $_SERVER['HTTP_REFERER'];
        mod_msgbox::show("用户管理", "日志删除成功", $gourl);
    }

    /**
     * 登录日志
     */
    public function login_log()
    {
        $where = array();
        $url = "";
        $keyword = req::item('keyword', '');
        if (!empty($keyword)) 
        {
            $where[] = "CONCAT(`accounts`, `loginip`) LIKE '%{$keyword}%'";
            $url = "&keyword=" . $keyword;
        }
        $where = empty($where) ? '' : 'WHERE ' . implode(' AND ', $where);

        $sql = "SELECT COUNT(*) AS count FROM `users_login_history` {$where}";
        $row = db::get_one($sql);
        $config['current_page'] = req::item('page_no', 1);   //当前页数,至少为1
        $config['page_size']    = 20;      //每页显示多少条
        $config['total_rs']     = $row['count'];      //总记录数
        $config['url_prefix']   = '?ct=users&ac=login_log' . $url;     //网址前缀
        $config['page_name']    = 'page_no';  //当前分页变量名(默认是page_no,即访问是用 url_prefix&page_no=xxx )
        $config['move_size']    = 5;    //前后偏移量（默认是5）
        $config['input']        = 0;    //是否使用输入跳转框(0|1)
        $pages = util::pagination($config);

        $offset = ( $config['current_page'] - 1 ) * $config['page_size'];
        $sql = "SELECT * FROM `users_login_history` {$where} ORDER BY `autoid` DESC LIMIT {$offset}, {$config['page_size']}";
        $list = db::get_all($sql);

        //echo '<pre>';print_r($list);echo '</pre>';
        tpl::assign( 'list', $list );
        tpl::assign( 'pages', $pages );
        tpl::display( 'users.login_log.tpl' );
    }

    /**
     * 删除操作日志
     */
    public function login_log_del()
    {
        $ids = req::item('autoid', array());
        if (empty($ids)) 
        {
            mod_msgbox::show("用户管理", "删除失败,请选择要删除的登陆日志", -1);
        }

        $ids = implode(',', $ids);
        $sql = "DELETE FROM `users_login_history` WHERE `autoid` IN ({$ids})";
        db::query($sql);
        $gourl = empty($_SERVER['HTTP_REFERER']) ? '?ct=users&ac=login_log' : $_SERVER['HTTP_REFERER'];
        mod_msgbox::show("用户管理", "登陆日志删除成功", $gourl);
    }

    /**
     * 清空旧的登录日志
     */
    public function del_old_login_log()
    {
        $log_name = 'login-log-'.date('Y-m', time());
        $three_mo = time() - (3600 * 24 * 90);
        $rs = db::query("Select * From `users_login_history` where `logintime` < {$three_mo} ");
        $tmp = '';
        $i = $n = 0;
        while( $row = db::fetch_one($rs) )
        {
            $i++;
            $n++;
            if( $i > 200 )
            {
                log::add($log_name, $tmp);
                log::save();
                $tmp = '';
                $i = 0;
            } else {
                $tmp .= $row['autoid']."\t".$row['uid']."\t".$row['accounts']."\t".$row['loginip']."\t".date('Y-m-d H:i:s', $row['logintime'])."\t".$row['pools']."\t".$row['loginsta']."\n";
            }
        }
        if( $tmp != '' )
        {
            log::add($log_name, $tmp);
            log::save();
        }
        db::query("Delete From `users_login_history` where `logintime` < {$three_mo} ", true);
        mod_msgbox::show('系统提示', "成功清理 {$n} 条旧登录日志！", '?ct=users&ac=login_log');
        exit();
    }

    /**
     * 登录IP限制
     */
    public function iplimit()
    {
        $ips = req::item('ips', '');
        if( empty($ips) )
        {
            $ips = cls_access_cfg::get_config( 'ip_limit' );
            tpl::assign('ips', $ips);
            tpl::display('users.iplimit.tpl');
        }
        else
        {
            cls_access_cfg::save_config('ip_limit', $ips);
            mod_msgbox::show('系统提示', '成功修改IP限制配置', '?ct=users&ac=iplimit');
        }
    }

    /**
     * 全局权限xml配置
     */
    public function edit_purview_xml()
    {
        $purview_xml = req::item('purview_xml', '');
        if( empty($purview_xml) )
        {
            $purview_xml = cls_access_cfg::get_config( 'purview_xml' );
            tpl::assign('purview_xml', $purview_xml);
            tpl::display('users.edit_purview_xml.tpl');
        }
        else
        {
            cls_access_cfg::save_config('purview_xml', $purview_xml);
            mod_msgbox::show('系统提示', '成功修改权限xml配置', '?ct=users&ac=edit_purview_xml');
        }
    }

    public static function get_config_apps()
    {
        $config_apps = array();
        // 废弃，不想额外创建一个权限管理的数据, 反正用一个文件处理2者选一
        // require(PATH_CONFIG.'/inc_groups_name.php');
        // $config_apps = $config['apps'];
        $menu_config = file_get_contents(PATH_CONFIG.'/inc_admin_menu.php');
        preg_match_all("#<menu([^>]*)>(.*)</menu>#sU", $menu_config, $arr);
        foreach($arr[1] as $k=>$v)
        {
            $atts = self::parse_atts($v);
            $menu_name = self::get_att($atts, 'name');
            if( trim($arr[2][$k]) == '') continue;
            preg_match_all("#<node([^>]*)>(.*)</node>#sU", $arr[2][$k], $nodes);
            foreach($nodes[1] as $n=>$n_v)
            {
                $is_continue = false;
                $atts = self::parse_atts($n_v);
                $n_name  = self::get_att($atts, 'name');
                //echo $menu_name . " === " . $n_name . "<br />";
                preg_match("#<item([^>]*)/>#sU", $nodes[2][$n], $items);
                $atts = self::parse_atts($items[1]);
                $i_ct = self::get_att($atts, 'ct');
                if (!isset($config_apps[$i_ct]['app_name']))
                {
                    $config_apps[$i_ct]['app_name'] = $menu_name . "-" . $n_name;
                }
                preg_match_all("#<item([^>]*)/>#sU", $nodes[2][$n], $items);
                foreach($items[1] as $i=>$i_v)
                {
                    $atts = self::parse_atts($i_v);
                    $i_name = self::get_att($atts, 'name');
                    $i_ct = self::get_att($atts, 'ct');
                    $i_ac = self::get_att($atts, 'ac');
                    $config_apps[$i_ct][$i_ac] = $i_name;
                }
            }
        }
        return $config_apps;
    }

}
